<script setup>
import { ref } from 'vue'
import navbar from './navbar.vue'
import api from '@/api'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh'
dayjs.locale('zh')
dayjs.extend(relativeTime)

const router = useRouter()

const categories = ref([])

const category = ref(null)

const sortValue = ref('time')
const sortOptions = ref([
  { value: 'time', text: '时间排序' },
  { value: 'favorite', text: '收藏排序' },
  { value: 'use', text: '使用排序' },
])

const materials = ref([])
const materialsPage = ref(1)
const materialsTotal = ref(0)
const materialsLoading = ref(false)
const materialsFinished = ref(false)
const materialsRefreshing = ref(false)

const popupCategoryVisible = ref(false)

const changeCategory = (item) => {
  category.value = item
  popupCategoryVisible.value = false

  getMaterials()
}

const getCategories = async () => {
  categories.value = await api.get('ip/material/categories')
  if (categories.value.length) {
    category.value = categories.value[0]
  }
}

const getMaterials = async () => {
  materialsLoading.value = true
  materialsPage.value = 1
  materialsFinished.value = false
  materials.value = []
  materialsTotal.value = 0
  try {
    const resp = await api.get('ip/materials', { params: { category_id: category.value.id, sort: sortValue.value } })
    materials.value = resp.data
    materialsTotal.value = resp.total
    if (materials.value.length == resp.total) {
      materialsFinished.value = true
    }
  } catch (error) {
    console.error(error)
  }
  materialsLoading.value = false
  materialsRefreshing.value = false
}

const onLoad = async () => {
  if (category.value && !materialsFinished.value) {
    try {
      materialsPage.value += 1
      const resp = await api.get('ip/materials', { params: { category_id: category.value.id, page: materialsPage.value, sort: sortValue.value } })
      if (resp.data.length) {
        materials.value.push(...resp.data)
        materialsTotal.value = resp.total
      } else {
        materialsFinished.value = true
      }
    } catch (error) {
      console.error(error)
    }
  }
  materialsLoading.value = false
}

const onRefresh = async () => {
  getMaterials()
}

const changeSort = () => {
  getMaterials()
}

;(async () => {
  await getCategories()

  await getMaterials()
})()

const keyword = ref('')
const onSearch = () => {
  if (keyword.value) {
    router.push('/ip/materials/search?keyword=' + keyword.value)
  }
}
</script>

<template>
  <div class="container">
    <div class="header">
      <div class="input">
        <van-icon class="icon" name="search" />
        <input type="text" v-model.trim="keyword" placeholder="请输入关键词搜索素材" />
        <div class="btn" @click="onSearch">搜索</div>
      </div>

      <div class="catelog">
        <div class="categories">
          <div class="category" :class="{ active: category && category.id == item.id }" @click="changeCategory(item)" v-for="item in categories.slice(0, 4)">
            <div class="icon">
              <img :src="item.image" />
            </div>
            <div class="name">{{ item.name }}</div>
          </div>
        </div>

        <div class="right">
          <div class="category" @click="popupCategoryVisible = true">
            <div class="icon">
              <img src="@/assets/img/qbfl.png" />
            </div>
            <div class="name">全部分类</div>
          </div>

          <div class="category" @click="router.push('/ip/my')">
            <div class="icon">
              <img src="@/assets/img/wdsc.png" />
            </div>
            <div class="name">个人中心</div>
          </div>
        </div>
      </div>
    </div>

    <div class="action">
      <van-dropdown-menu class="sort-menu">
        <van-dropdown-item v-model="sortValue" :options="sortOptions" @change="changeSort" />
      </van-dropdown-menu>
      <div class="total">共 {{ materialsTotal }} 个素材</div>
    </div>

    <van-pull-refresh class="list" v-model="materialsRefreshing" @refresh="onRefresh">
      <van-list v-model:loading="materialsLoading" :finished="materialsFinished" :finished-text="materials.length && !materialsLoading ? '没有更多了' : '暂无素材'" @load="onLoad">
        <div class="materials" style="margin-top: 3vw">
          <div class="material" v-for="item in materials" @click="router.push(`/ip/materials/${item.id}`)">
            <div class="body">
              <div class="title">{{ item.title }}</div>
              <div class="content">{{ item.content }}</div>
              <div class="footer">
                <div class="category-name">{{ item.category.name }}</div>

                <div class="count">
                  <img src="@/assets/img/sc.png" />
                  {{ item.favorite_count }}
                </div>

                <div class="count">
                  <img src="@/assets/img/tk.png" />
                  {{ item.video_count }}
                </div>
                <div class="count">{{ dayjs(item.created_at).fromNow() }}</div>
              </div>
            </div>
            <div class="image">
              <img :src="item.image" />
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <van-popup class="popup-categories" v-model:show="popupCategoryVisible" position="top">
      <div class="categories">
        <div class="category" :class="{ active: category.id == item.id }" @click="changeCategory(item)" v-for="item in categories">
          <div class="icon">
            <img :src="item.image" />
          </div>
          <div class="name">{{ item.name }}</div>
        </div>
      </div>
    </van-popup>

    <navbar></navbar>
  </div>
</template>

<style lang="scss" scoped>
.list {
  min-height: 40vh;
}
.container {
  background: #f2f2f2;
  height: 100vh;
  overflow: auto;
  padding-bottom: 16vw;
}
.header {
  background-image: linear-gradient(360deg, #ffffff 0%, #e4efff 100%);
  overflow: hidden;
}

.input {
  border: 1px solid #d6dbe3;
  display: flex;
  margin: 2vw 6vw;
  border-radius: 50px;
  padding: 0.3vw;
  align-items: center;

  input {
    flex: 1;
    display: block;
    border: none;
    outline: none;
    background: none;
    padding-left: 1vw;

    &::placeholder {
      font-family: PingFangSC-Regular;
      font-size: 3.5vw;
      color: rgba(0, 0, 0, 0.25);
      letter-spacing: 0;
      font-weight: 400;
    }
  }

  .icon {
    color: rgba(0, 0, 0, 0.25);
    font-size: 6vw;
    margin-left: 1.6vw;
  }

  .btn {
    background: #134bbb;
    font-family: PingFangSC-Regular;
    font-size: 3.5vw;
    color: #ffffff;
    letter-spacing: 0;
    text-align: center;
    font-weight: 400;
    padding: 1.5vw 4vw;
    border-radius: 50px;
  }
}

.catelog {
  margin-top: 4vw;
  display: flex;

  .right {
    border-left: 1px solid #ebebeb;
    display: flex;
    margin-left: auto;
  }

  border-bottom: 1px solid #f2f2f2;
  padding-bottom: 2vw;

  .categories {
    display: flex;
  }

  .category {
    font-family: PingFangSC-Regular;
    font-size: 3.2vw;
    letter-spacing: 0;
    font-weight: 400;
    flex-shrink: 0;
    width: 16.5vw;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: rgba(92, 92, 92, 0.6);
    position: relative;

    &.active {
      color: rgba(0, 0, 0, 0.9);
    }
    &.active::after {
      content: '';
      width: 30%;
      height: 0.8vw;
      background: #134bbb;
      position: absolute;
      bottom: -2vw;
    }

    .icon {
      width: 8.5vw;
      height: 8.5vw;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        display: block;
        max-width: 100%;
        max-height: 100%;
      }
    }

    .name {
      margin-top: 1vw;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
      text-align: center;
    }
  }
}

.action {
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 2vw;

  .total {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.3);
    letter-spacing: 0;
    text-align: right;
    font-weight: 400;
  }
}

.sort-menu {
  :deep(.van-dropdown-menu__bar) {
    box-shadow: none;
    height: 10vw;

    .van-dropdown-menu__title {
      font-family: PingFangSC-Regular;
      font-size: 3.8vw;
      color: rgba(0, 0, 0, 0.8);
      letter-spacing: 0;
      text-align: center;
      font-weight: 400;
    }
  }
}

.popup-categories {
  padding-bottom: 3.36vw;
  .categories {
    .category {
      width: 20.8vw;
      height: 20.8vw;
      border: 1px solid #ededed;
      border-radius: 8px;
      float: left;
      margin-left: 3.36vw;
      margin-top: 3.36vw;

      font-family: PingFangSC-Regular;
      font-size: 3vw;
      color: rgba(0, 0, 0, 0.65);
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;

      &.active {
        border: 1px solid #134bbb;
        color: #134bbb;
      }

      .icon {
        width: 8.5vw;
        height: 8.5vw;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 2vw;

        img {
          display: block;
          max-width: 100%;
          max-height: 100%;
        }
      }
    }
  }
}
</style>
